import os
import subprocess
import time

def should_update():
    return os.getenv("AUTO_UPDATE_ENABLED", "false").lower() == "true"

def run(cmd, cwd=None):
    subprocess.run(cmd, cwd=cwd, check=True)

def changed(repo_dir, branch):
    run(["git", "fetch", "origin", branch], cwd=repo_dir)
    local = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo_dir).strip()
    remote = subprocess.check_output(["git", "rev-parse", f"origin/{branch}"], cwd=repo_dir).strip()
    return local != remote

def update(compose_path):
    run(["docker-compose", "-f", compose_path, "build"])
    run(["docker-compose", "-f", compose_path, "up", "-d"])

def main():
    interval = int(os.getenv("AUTO_UPDATE_INTERVAL", "60"))
    branch = os.getenv("GIT_BRANCH", "main")
    repo_dir = os.getenv("REPO_DIR", "/workspace")
    compose_path = os.getenv("COMPOSE_FILE_PATH", "/workspace/docker-compose.yml")
    while True:
        if should_update():
            try:
                if changed(repo_dir, branch):
                    run(["git", "reset", "--hard", f"origin/{branch}"], cwd=repo_dir)
                    update(compose_path)
            except Exception:
                pass
        time.sleep(interval)

if __name__ == "__main__":
    main()
